package com.chaoyue.auth.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.chaoyue.auth.beans.dto.AuthParamsDto;
import com.chaoyue.auth.beans.dto.CyUserExt;
import com.chaoyue.auth.beans.po.CyMenu;
import com.chaoyue.auth.ucenter.mapper.CyMenuMapper;
import com.chaoyue.auth.ucenter.mapper.CyUserMapper;

import com.chaoyue.auth.ucenter.service.AuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author whr
 * @version 1.0
 * @description: TODO
 * @date 2023/5/28 19:04
 */
@SuppressWarnings({"all"})
@Component
@Slf4j
public class UserServiceImpl implements UserDetailsService {
    @Autowired
    CyUserMapper xcUserMapper;
    @Autowired
    ApplicationContext applicationContext;
@Autowired
CyMenuMapper xcMenuMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("类型转化异常");
        }
        String authType = authParamsDto.getAuthType();
        String username = authParamsDto.getUsername();
        String beanName=authType+"_authservice";
        AuthService bean = applicationContext.getBean(beanName, AuthService.class);
        CyUserExt xcUserExt = bean.execute(authParamsDto);
        return getUserPrincipal(xcUserExt);
    }
    public UserDetails getUserPrincipal(CyUserExt user){
        String password = user.getPassword();
        String id = user.getId();
        List<CyMenu> xcMenus = xcMenuMapper.selectPermissionByUserId(id);
        String[] authorities = null;
        if(xcMenus.size()>0) {
            ArrayList<String> codes = new ArrayList<>();
            xcMenus.forEach(item -> {
                codes.add(item.getCode());
            });
            authorities=codes.toArray(new String[0]);
        }
        user.setPassword(null);
        String userJson = JSON.toJSONString(user);
        UserDetails userDetails = User.withUsername(userJson).password(password).authorities(authorities).build();
        return userDetails;
    }
}
